from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.options.common.base import AppiumOptions
import subprocess
import time
import os
from datetime import datetime


def start_thunder_emulator(emulator_index=0):
    """启动雷电模拟器"""
    try:
        print("🚀 正在启动雷电模拟器...")
        ld_path = r"D:\Tools\雷电模拟器\LDPlayer9\ldconsole.exe"

        if os.path.exists(ld_path):
            cmd = f'"{ld_path}" launch --index {emulator_index}'
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
            if result.returncode == 0:
                print("✅ 雷电模拟器启动命令执行成功")
            else:
                print("⚠️ 无法通过命令行启动，请手动启动雷电模拟器")
        else:
            print("⚠️ 未找到雷电模拟器命令行工具，请手动启动雷电模拟器")

        # 等待模拟器启动
        print("⏳ 等待模拟器启动...")
        time.sleep(5)

        # 检查ADB连接
        return wait_for_adb_connection()

    except Exception as e:
        print(f"❌ 启动雷电模拟器失败: {e}")
        print("💡 请手动启动雷电模拟器后继续...")
        return False


def wait_for_adb_connection(timeout=60):
    """等待ADB设备连接"""
    print("🔍 检查ADB设备连接...")
    start_time = time.time()

    while time.time() - start_time < timeout:
        try:
            result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
            if 'emulator-5554' in result.stdout and 'device' in result.stdout:
                print("✅ ADB设备连接成功")
                return True
        except:
            pass

        print("⏳ 等待设备连接...")
        time.sleep(5)

    print("❌ ADB设备连接超时")
    return False


def connect_appium():
    """连接Appium服务器并返回driver对象"""
    try:
        print("🔗 正在连接Appium服务器...")

        # Appium配置
        desired_caps = {
            'platformName': 'Android',
            'platformVersion': '9',
            'deviceName': 'emulator-5554',
            'automationName': 'UiAutomator2',
            'noReset': True,
            'newCommandTimeout': 300,
            'unicodeKeyboard': True,
            'resetKeyboard': True,
        }

        # 显示连接配置
        print("📋 连接配置:")
        for key, value in desired_caps.items():
            print(f"   {key}: {value}")

        # 使用AppiumOptions
        options = AppiumOptions()
        for key, value in desired_caps.items():
            options.set_capability(key, value)

        # 尝试不同的URL端点
        appium_urls = [
            'http://127.0.0.1:4723/wd/hub',  # 传统端点
            'http://127.0.0.1:4723',  # 新版本端点
        ]

        for appium_url in appium_urls:
            try:
                print(f"🔄 尝试连接: {appium_url}")
                driver = webdriver.Remote(
                    command_executor=appium_url,
                    options=options
                )
                print(f"✅ Appium连接成功！使用URL: {appium_url}")
                return driver

            except Exception as url_error:
                print(f"❌ {appium_url} 失败: {url_error}")
                continue

        print("❌ 所有URL端点都连接失败")
        return None

    except Exception as e:
        print(f"❌ Appium连接失败: {e}")
        return None


def get_device_info(driver):
    """获取设备信息"""
    if not driver:
        print("❌ 未连接到Appium")
        return

    try:
        print("\n📊 设备详细信息:")
        print(f"设备品牌: {driver.capabilities.get('deviceManufacturer', 'Unknown')}")
        print(f"设备型号: {driver.capabilities.get('deviceModel', 'Unknown')}")
        print(f"系统版本: {driver.capabilities.get('platformVersion', 'Unknown')}")
        print(f"屏幕分辨率: {driver.get_window_size()}")

        try:
            print(f"当前包名: {driver.current_package}")
            print(f"当前Activity: {driver.current_activity}")
        except:
            print("当前应用: 信息不可用")

    except Exception as e:
        print(f"❌ 获取设备信息失败: {e}")


def take_screenshot(driver, screenshot_dir="screenshots", name=None):
    """截取屏幕截图"""
    if not driver:
        print("❌ 未连接到Appium，无法截图")
        return None

    # 创建截图目录
    if not os.path.exists(screenshot_dir):
        os.makedirs(screenshot_dir)

    try:
        # 生成截图文件名
        if name is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            name = f"screenshot_{timestamp}"

        filename = f"{screenshot_dir}/{name}.png"

        # 截取截图
        driver.save_screenshot(filename)
        print(f"📸 截图已保存: {filename}")

        return filename

    except Exception as e:
        print(f"❌ 截图失败: {e}")
        return None


def open_app(driver, app_package, app_activity):
    """打开指定应用"""
    if not driver:
        print("❌ 未连接到Appium")
        return False

    try:
        print(f"📱 打开应用: {app_package}")
        driver.start_activity(app_package, app_activity)
        time.sleep(3)
        print("✅ 应用打开成功")
        return True
    except Exception as e:
        print(f"❌ 打开应用失败: {e}")
        return False


def open_settings(driver):
    """打开设置应用"""
    return open_app(driver, 'com.android.settings', 'com.android.settings.Settings')


def go_home(driver):
    """返回主页"""
    if not driver:
        return False

    try:
        print("🏠 返回主页")
        driver.press_keycode(3)  # KEYCODE_HOME
        time.sleep(2)
        return True
    except Exception as e:
        print(f"❌ 返回主页失败: {e}")
        return False


def press_back(driver):
    """按返回键"""
    if not driver:
        return False

    try:
        print("↩️ 按下返回键")
        driver.press_keycode(4)  # KEYCODE_BACK
        time.sleep(1)
        return True
    except Exception as e:
        print(f"❌ 返回键失败: {e}")
        return False


def click_element(driver, by, value):
    """点击元素"""
    if not driver:
        print("❌ 未连接到Appium")
        return False

    try:
        # 简单等待
        time.sleep(1)
        element = driver.find_element(by, value)
        element.click()
        print(f"✅ 点击元素: {by}={value}")
        return True
    except Exception as e:
        print(f"❌ 点击元素失败: {by}={value}, 错误: {e}")
        return False


def click_by_text(driver, text):
    """通过文本点击元素"""
    return click_element(
        driver,
        AppiumBy.ANDROID_UIAUTOMATOR,
        f'new UiSelector().text("{text}")'
    )


def click_by_id(driver, element_id):
    """通过ID点击元素"""
    return click_element(driver, AppiumBy.ID, element_id)


def click_by_description(driver, description):
    """通过描述点击元素"""
    return click_element(driver, AppiumBy.ACCESSIBILITY_ID, description)


def input_text(driver, by, value, text):
    """输入文本"""
    if not driver:
        print("❌ 未连接到Appium")
        return False

    try:
        time.sleep(1)
        element = driver.find_element(by, value)
        element.clear()
        element.send_keys(text)
        print(f"✅ 输入文本: {text}")
        return True
    except Exception as e:
        print(f"❌ 输入文本失败: {e}")
        return False


def close_connection(driver):
    """关闭连接"""
    if driver:
        driver.quit()
        print("✅ Appium连接已关闭")


def main():
    """主函数 - 从上到下依次执行"""
    driver = None

    try:
        print("=" * 50)
        print("🚀 雷电模拟器自动化操作")
        print("=" * 50)

        # 启动雷电模拟器
        print("\n1. 启动雷电模拟器")
        if not start_thunder_emulator():
            print("❌ 模拟器启动失败，退出程序")
            return

        # 连接Appium
        print("\n2. 连接Appium服务器")
        driver = connect_appium()
        if not driver:
            print("❌ Appium连接失败，退出程序")
            return

        # 获取设备信息
        print("\n3. 获取设备信息")
        get_device_info(driver)

        # 软件点击
        elements = driver.find_elements(AppiumBy.CLASS_NAME, "android.widget.TextView")
        element1 = elements[2]
        element1.click()
        print("点击软件")
        time.sleep(10)

        # 买商品
        elements = driver.find_elements(AppiumBy.CLASS_NAME, "android.widget.TextView")
        element1 = elements[1]
        element1.click()
        print("点击买商品")
        time.sleep(2)

        # 筛选1
        element = driver.find_element(AppiumBy.ID, "com.uu898.uuhavequality:id/filter_iv")
        element.click()
        print("点击筛选1")
        time.sleep(2)

        # 应用按钮
        element = driver.find_element(AppiumBy.ID, "com.uu898.uuhavequality:id/tvManagerLayout")
        element.click()
        print("点击应用按钮")
        time.sleep(2)

        # 点击第一个商品
        elements = driver.find_elements(AppiumBy.CLASS_NAME, "android.view.ViewGroup")
        element1 = elements[0]
        element1.click()
        print("点击第一个商品")
        time.sleep(2)



    except Exception as e:
        print(f"💥 程序执行出错: {e}")

    finally:
        # 确保关闭连接
        if driver:
            input("\n按Enter键关闭连接...")
            close_connection(driver)


if __name__ == "__main__":
    main()